<template>
  <div class="app-container">
    <div class="container">
      <el-dialog
        :title="state ? '添加用户' : '修改用户'"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        width="30%"
      >
        <el-form
          ref="ruleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col>
              <el-form-item label="角色名" prop="roleName">
                <el-input v-model="roleForm.roleName" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="角色码" prop="roleCode">
                <el-input v-model="roleForm.roleCode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="角色描述">
                <el-input v-model="roleForm.description" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              state ? '添加' : '修改'
            }}</el-button>
            <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          </el-form-item>
        </el-form>
      </el-dialog>
      <div class="operate-box">
        <div class="input-box">
          <el-input
            v-model.trim="conds.keyword"
            size="small"
            placeholder="请输入内容"
          />
          <el-button
            type="primary"
            size="small"
            plain
            icon="el-icon-search"
            @click="search"
            >搜索</el-button
          >
        </div>
        <div class="btn-box operate-btn">
          <el-button
            type="success"
            size="small"
            plain
            icon="el-icon-check"
            :disabled="$hasBP('bnt.sysRole.add') === false"
            @click="addUser"
            >添加</el-button
          >
          <el-popconfirm title="确定批量永久删除吗？" :disabled="$hasBP('bnt.sysRole.remove') == false" @confirm="batchDel">
            <el-button
              slot="reference"
              type="danger"
              size="small"
              plain
              icon="el-icon-delete"
              >删除</el-button
            >
          </el-popconfirm>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        tooltip-effect="dark"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column align="center" type="index" label="ID" width="45" />
        <el-table-column label="角色名" align="center">
          <template slot-scope="scope">
            {{ scope.row.roleName }}
          </template>
        </el-table-column>
        <el-table-column label="角色码" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template slot-scope="scope">
            {{ scope.row.description }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="created_at"
          label="创建时间"
          width="200"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.createTime">
              <i class="el-icon-time" />&nbsp;
              <span>{{ scope.row.createTime | formattedDate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="created_at"
          label="修改时间"
          width="200"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.updateTime">
              <i class="el-icon-time" />&nbsp;
              <span>{{ scope.row.updateTime | formattedDate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="operate">
            <el-button
              type="primary"
              circle
              size="small"
              icon="el-icon-edit"
              :disabled="$hasBP('bnt.sysRole.update') == false"
              @click="editUser(operate.row)"
            />
            &nbsp;
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              circle
              title="分配权限"
              :disabled="$hasBP('bnt.sysRole.update') == false"
              @click="showAssignAuth(operate.row)"
            />
            &nbsp;
            <el-popconfirm
              title="确定删除吗？"
              :disabled="$hasBP('bnt.sysRole.remove') == false"
              @confirm="deleteUser(operate.row)"
            >
              <el-button
                slot="reference"
                type="danger"
                circle
                size="small"
                icon="el-icon-delete"
              />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="conds.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="conds.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { updateStatus, getList, remove, saveOrUpdate } from '@/api/role'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      }
      return statusMap[status]
    },
    formattedDate(time) {
      const date = new Date(time)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      const second = date.getSeconds().toString().padStart(2, '0')
      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`
      return formattedDate
    },
  },
  data() {
    return {
      state: true,
      dialogVisible: false,
      list: null,
      listLoading: true,
      currentPage: 1,
      conds: {
        page: 1,
        size: 5,
        total: 0,
        keyword: '',
      },
      roleForm: {
        id: null,
        roleName: null,
        roleCode: null,
        description: null,
      },
      multipleSelection: [],
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.state) {
            saveOrUpdate(this.roleForm)
            this.dialogVisible = false
            this.fetchData()
            this.$message({
              message: '添加成功',
              type: 'success',
            })
            this.roleForm = {}
          } else {
            saveOrUpdate(this.roleForm).then((res) => {
              if (res.code === 200) {
                this.dialogVisible = false
                this.$message({
                  message: '修改成功',
                  type: 'success',
                })
                this.fetchData()
                this.roleForm = {}
              } else {
                this.$message({
                  message: '修改失败',
                  type: 'error',
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose(done) {
      this.dialogVisible = false
      this.roleForm = {}
    },
    search() {
      this.fetchData()
    },
    async batchDel() {
      const data = await remove(this.multipleSelection)
      if (data.code === 200) {
        this.$message({
          message: '删除成功',
          type: 'success',
        })
        this.fetchData()
      } else {
        this.$message({
          message: data.message,
          tyep: 'error',
        })
      }
    },
    async deleteUser(row) {
      console.log(row)
      const data = await remove([row.id])
      if (data.code === 200) {
        this.$message({
          message: '删除成功',
          type: 'success',
        })
        this.fetchData()
      } else {
        this.$message({
          message: data.message,
          tyep: 'error',
        })
      }
    },
    addUser() {
      this.state = true
      this.dialogVisible = true
      this.roleForm = {}
    },
    editUser(row) {
      this.state = false
      const old = JSON.parse(JSON.stringify(row))
      this.roleForm = old
      this.dialogVisible = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.conds.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.conds.page = val
      this.fetchData()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id)
      console.log(this.multipleSelection)
    },
    fetchData() {
      this.listLoading = true
      getList(this.conds).then((response) => {
        this.list = response.data.records
        this.conds.total = response.data.total
        this.conds.page = response.data.current
        this.conds.size = response.data.size
        this.listLoading = false
      })
    },
    async change(row) {
      const data = await updateStatus(row)
      if (data.code === 200) {
        this.fetchData()
        this.$message({
          message: '修改成功',
          type: 'success',
        })
      } else {
        this.$message({
          message: '修改失败',
          type: 'error',
        })
      }
    },
    showAssignAuth(row) {
      console.log(row)
      this.$router.push(
        '/system/assignAuth?id=' + row.id + '&roleName=' + row.roleName
      )
    },
  },
}
</script>

<style lang="scss">
.el-pagination {
  height: 30px;
  margin-top: 20px;
  text-align: center;
}

.operate-box {
  display: flex;
  margin-bottom: 20px;
}

.input-box {
  display: flex;
  width: 250px;
  .el-input {
    margin-right: 10px;
  }
}

.btn-box.operate-btn .el-button:not(:last-child) {
  margin-right: 10px;
}

.btn-box {
  margin-left: 10px;
}

.el-button.el-button--warning {
  margin: 0;
}
</style>
